/**
 * 
 */
package com.shelpe.services.sinbad.configuration;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

import com.shelpe.services.sinbad.service.mq.ShelpeMQConsumerService;
import com.shelpe.services.sinbad.service.mq.impl.ShelpeMQConsumerServiceImpl;



/**
 * kafka消费者配置
 * @author louxinhua
 *
 */
@Configuration
@EnableKafka
@EnableConfigurationProperties(KafkaConfigProperties.class)
public class KafkaConsumerConfig {

	@Autowired
	private KafkaConfigProperties kafkaConfigProperties;
	
	
	@Bean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setPollTimeout(3000);
        return factory;
    }
	
	 public ConsumerFactory<String, String> consumerFactory() {
	        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
	    }
	
	 public Map<String, Object> consumerConfigs() {
	        Map<String, Object> propsMap = new HashMap<>();
	        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfigProperties.getAddress());
	        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); // 开启自动提交
	        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
	        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
	        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
	        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
	        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfigProperties.getGroupid());
	        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, kafkaConfigProperties.getAutoOffsetReset());
	        return propsMap;
	 }
	 
	 @Bean
	 public ShelpeMQConsumerService kafkaConsumer() {
		 return new ShelpeMQConsumerServiceImpl();
	 }
	
}
